/*  
 * Copyright (C) 2011 Marta Spodymek
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  
 */
package org.prometheuscode.web.feedback.filestrategy;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.prometheuscode.web.feedback.ApplicationConfig;
import org.prometheuscode.web.feedback.domain.IFeed;
import org.prometheuscode.web.feedback.file.FileInfo;
import org.prometheuscode.web.feedback.file.FileStrategyInfo;

/**
 * This class knows how to create saving strategy for file saver.
 * 
 * By default it saves file in:
 * 
 * application root / feed-data / {user} / {feedType} / {feedId} / filename
 * 
 * TODO allow it to be configured from the XML file.
 * 
 * @author marta
 * 
 */
public class SavingStrategyConfiguration implements IFileStrategyConfiguration {

    private ApplicationConfig config;

    public SavingStrategyConfiguration() {
    }

    public ApplicationConfig getConfig() {
	return this.config;
    }

    public void setConfig(ApplicationConfig config) {
	this.config = config;
    }

    @Override
    public FileStrategyInfo createStrategy(IFeed feed, List<FileInfo> files,
	    Map<String, String> params) {

	String rootPath = this.config.getServletContext().getRealPath("/");
	String userName = feed.getUser().getLogin();
	String feedId = feed.getId();
	String type = feed.getType();
	String dynamicPath = "/feed-data/" + userName + "/" + type + "/"
		+ feedId;
	String targetPath = rootPath + dynamicPath;

	/* configure params and paths for file saver */
	Map<String, String> saveHandlerParams = new HashMap<String, String>();
	for (FileInfo fileInfo : files) {
	    String postedName = fileInfo.getInfo(FileInfo.POSTED_NAME_INFO);
	    String fileNameToSave = postedName + "-"
		    + fileInfo.getInfo(FileInfo.FILE_NAME_INFO);
	    params.put(postedName, dynamicPath + "/" + fileNameToSave);
	    saveHandlerParams
		    .put(postedName, targetPath + "/" + fileNameToSave);
	}

	FileStrategyInfo info = new FileStrategyInfo(feedId, files,
		saveHandlerParams);
	return info;
    }

}
